package com.app.sgd.controller.action;

import java.util.ArrayList;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.app.sgd.business.dao.OracleExpedienteDAO;
import com.app.sgd.business.dao.SQLDocumentoDAO;
import com.app.sgd.manager.SGDDispatchAction;
import com.app.sgd.model.bean.ExpedienteBCA;
import com.app.sgd.model.bean.TempUploadTramite;
import com.app.sgd.model.bean.Usuario;
import com.app.sgd.util.Constants;
import com.app.sgd.util.DownloadUtil;
import com.app.sgd.util.SessionConstants;
import com.app.sgd.util.Util;
import com.app.sgd.view.actionform.AdministracionDocumentoForm;

public class DownloadDocContenidoAction extends SGDDispatchAction{
	public ActionForward downloadDocumento(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) throws Exception {
		
		AdministracionDocumentoForm formdoc = (AdministracionDocumentoForm)form;
		Usuario usuario = (Usuario)request.getSession().getAttribute(SessionConstants.SGD_USUARIO_SESION_ACTIVO);
		SQLDocumentoDAO sqlDocumentoDAO = new SQLDocumentoDAO();
		
		String accion = request.getParameter("accion");
		String docId = request.getParameter("DocId");
		String aniodoc = request.getParameter("aniodoc");
		boolean edicion = (request.getParameter("Edicion")!=null && request.getParameter("Edicion").trim().equals("Si")) ? true : false;
		boolean reempCmps = (request.getParameter("ReempCamposEspeciales")!=null && request.getParameter("ReempCamposEspeciales").trim().equals("Si")) ? true : false; 
		int destNroInt = (request.getParameter("DestNro") != null && request.getParameter("DestNro").trim().length() > 0) ? Integer.parseInt(request.getParameter("DestNro")) : -1;
		String segId = (request.getParameter("SegId")!= null && request.getParameter("SegId").trim().length() > 0) ? request.getParameter("SegId") : "-1"; 
		String tipoDocId = formdoc.getCodTipoDocumento();
		String tipoMovId = formdoc.getCodMovimiento();
		
		TempUploadTramite tempUploadTramite = new TempUploadTramite();
		tempUploadTramite.setCodDocumento(docId);
		tempUploadTramite.setNombreDocWord(docId+".doc");
		tempUploadTramite.setNombreDocPDF(docId+".pdf");
		tempUploadTramite.setEstadoDocumento(Constants.VALOR_DEFAULT_UNO);
		tempUploadTramite.setCodUsuarioAud(usuario.getCodigo());
		tempUploadTramite.setCodEmpleadoAud(usuario.getCodigo());
		tempUploadTramite.setCodAreaAud(usuario.getEncargaturaPerfil().getCodArea());
		tempUploadTramite.setDireccionIPAud(usuario.getDireccionIP());
		tempUploadTramite.setLoginUsr(usuario.getLogin());
		tempUploadTramite.setTipoMovimiento(Constants.VALOR_DEFAULT_CERO);
		tempUploadTramite.setTipoDocumento(Constants.VALOR_DEFAULT_CERO);
		tempUploadTramite.setCodSeguimiento(segId);
		tempUploadTramite.setFlgImpresion(Constants.NO);
		
		String tabla_documento_imagen = " DOCUMENTO_IMAGEN ";
		if(aniodoc.equals(Util.getDateAsStr(new Date()).substring(6,10)) 
				|| Integer.parseInt(aniodoc)>=Integer.parseInt(Constants.ANIO_TBL_DOCUMENTO)){
			tabla_documento_imagen = " DOCUMENTO_IMAGEN ";
		}
		else{
			if(aniodoc.trim().equals("") || aniodoc.trim().equals("null")) tabla_documento_imagen = " DOCUMENTO_IMAGEN ";
			else tabla_documento_imagen = " SGDOC_HIST_IMAGEN ";
		}
		
		boolean existeContenido = false;
		existeContenido = sqlDocumentoDAO.existeDocumentoWord(tabla_documento_imagen,tempUploadTramite);
		
		String documentonombre = tempUploadTramite.getNombreDocWord();//docId + ".doc";
		String vSQL = "";
		if (existeContenido) {
			if (edicion) {
				vSQL = "SELECT '" + documentonombre	+ "' as FileName"
						+"      ,DOC_IMAG_TDOC as FileContent "
						+"  FROM "+tabla_documento_imagen
						+" WHERE CODI_DOC_TDOC = " + docId;
			} else {
				vSQL =    "SELECT '" + documentonombre	+ "' as FileName"
						+ "      ,DOC_IMAGVP_TDOC as FileContent "
						+ "  FROM "+tabla_documento_imagen
						+ " WHERE CODI_DOC_TDOC = " + docId;
			}
		} else {
			vSQL = "SELECT '" + documentonombre	+ "' as FileName"
					+ "     ,DOC_IMA_TTD as FileContent "
					+ " FROM TIPODOC_MOVIMIENTO "
					+ "WHERE CODI_TMOV_TTM = " + tipoMovId 
					+ "  AND CODI_TDOC_TTD = " + tipoDocId;
		}
		
		

		if (reempCmps) {
			if (edicion && segId.equals("-1")) {
//				grabarTemDoc(docId, documentonombre, "1", usuarioInfo.getUsuarioId(), usuarioInfo.getEmpleadoId(),usuarioInfo.getAreaId(), request.getRemoteAddr(),usuarioInfo.getLogin(), tipoMovId, tipoDocId, segId,"N");
				sqlDocumentoDAO.grabarTemporalUpload(tempUploadTramite);
//				expedientes BCA
				try{
					OracleExpedienteDAO oracleExpedienteDAO = new OracleExpedienteDAO();
					int numExpediente = sqlDocumentoDAO.obtenerNumeroExpediente(Integer.parseInt(docId));
					if(numExpediente > 0){
						ArrayList lstExpedientesBCA = oracleExpedienteDAO.obtenerExpedientesBCA(numExpediente);
						ExpedienteBCA  expedienteBCA = lstExpedientesBCA.size()>0 ? (ExpedienteBCA)lstExpedientesBCA.get(0) : null;
						if(expedienteBCA!=null)
							sqlDocumentoDAO.grabarTemporalExpediente(Integer.parseInt(docId),expedienteBCA);
					}
				}catch(Exception e){e.printStackTrace();}
			}
			else {
				if (accion != null && accion.equals("imprimirSeleccion")) {
				}else if (accion != null && accion.equals("imprimirTodo")) {
				} else {
					tempUploadTramite.setEstadoDocumento(Constants.VALOR_DEFAULT_CERO);
					sqlDocumentoDAO.grabarTemporalUpload(tempUploadTramite);
					
//					expedientes BCA
					try{
						OracleExpedienteDAO oracleExpedienteDAO = new OracleExpedienteDAO();
						int numExpediente = sqlDocumentoDAO.obtenerNumeroExpediente(Integer.parseInt(docId));
						if(numExpediente > 0){
							ArrayList lstExpedientesBCA = oracleExpedienteDAO.obtenerExpedientesBCA(numExpediente);
							ExpedienteBCA  expedienteBCA = lstExpedientesBCA.size()>0 ? (ExpedienteBCA)lstExpedientesBCA.get(0) : null;
							if(expedienteBCA!=null)
								sqlDocumentoDAO.grabarTemporalExpediente(Integer.parseInt(docId),expedienteBCA);
						}
					}catch(Exception e){e.printStackTrace();}
				}
			}
		} 
		else {
			// caso de edicion de documento
			sqlDocumentoDAO.grabarTemporalUpload(tempUploadTramite);
			
//			expedientes BCA
			try{
				OracleExpedienteDAO oracleExpedienteDAO = new OracleExpedienteDAO();
				int numExpediente = sqlDocumentoDAO.obtenerNumeroExpediente(Integer.parseInt(docId));
				if(numExpediente > 0){
					ArrayList lstExpedientesBCA = oracleExpedienteDAO.obtenerExpedientesBCA(numExpediente);
					ExpedienteBCA  expedienteBCA = lstExpedientesBCA.size()>0 ? (ExpedienteBCA)lstExpedientesBCA.get(0) : null;
					if(expedienteBCA!=null)
						sqlDocumentoDAO.grabarTemporalExpediente(Integer.parseInt(docId),expedienteBCA);
				}
			}catch(Exception e){e.printStackTrace();}
		}
		
		if(edicion){
			DownloadUtil dUtil = new DownloadUtil(servlet, request, response);
			dUtil.outputDbFileContent(vSQL, null, null, "FileName", null,"FileContent");
		}
		else{
			DownloadUtil dUtil = new DownloadUtil(servlet, request, response);
			dUtil.outputDbFileContentPDF(vSQL, null, null, "FileName", tempUploadTramite.getNombreDocPDF(),"FileContent");
		}
		
		return null;
	}
	
	
	public ActionForward downloadDocAdjunto(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) throws Exception {
		String codDoc = request.getParameter("codDoc");
		
		String vSQL = "SELECT NAME_DOCAD_TDA AS FileName " +
				      "      ,DOC_ADJ_TDA AS FileContent " +
				      "  FROM DOCUMENTO_ADJUNTO " +
				      " WHERE CODI_DOCAD_TDA = ? " ;
	    
		new DownloadUtil(servlet, request, response).outputDbFileContent(vSQL, codDoc, null,  "FileName", null, "FileContent" );
	      
		return null;
	}
	
	public ActionForward downloadDocumentoPDF(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) throws Exception {
		AdministracionDocumentoForm formdoc = (AdministracionDocumentoForm)form;
		String rutaDocumentoPDF = formdoc.getRutaDocumentoPDF();
		
		new DownloadUtil(servlet, request, response).outputDocumentPDFContent(rutaDocumentoPDF);
		
		return null;
	}
}
